define(function(require, exports, module) {
	"use strict";
	require("../../dep/mui/js/mui.min.js");
	require("../jquery-3.1.1.min.js");
	require("../mui.picker.min.js");
	require("../dateShow.js");
	require("./dateInput.js");
	var globalInit = require("globalInit"); //共用js
	require("keepDate");
	var template = require("template");
	var updateSell = require("./updateSell.js");
	var abpUse = require("../abp.js");
	var muiTips = require("muiTips");
	var abp = abpUse.abpstart;
	require('http://g.alicdn.com/ilw/ding/0.8.9/scripts/dingtalk.js');

	var examinaSourceId = 0; //启用审批需传参数
	//返回清除缓存
	var dingTalkNav = require('dd_config');
	mui.init({
		swipeBack: true //启用右滑关闭功能
	});

	//钉钉右边按钮操作
	dingTalkNav.RightNavBar(false, "新增", "default");
	var getFunList = require("../getFunList/getFunList.js");
	//填充已选货品列表(从缓存加载)
	getFunList.addGoodsInfoList("goodsList", "#goodsListShow");

	$(function() {
		sessionStorage.removeItem("setParm");
		var allocateData = JSON.parse(sessionStorage.getItem("allotData"));
		var actionType = 1; //默认新增状态
		if(!allocateData) {
			//缓存为空（新增数据状态）

			//生成单号
			GenerateCode();
			sessionStorage.removeItem("allocateID");
		} else {
			examinaSourceId = Number(allocateData.id); //修改启用审批需传参数
			//缓存不为空（编辑状态）
			actionType = 2; //更新状态为修改状态
			$("#sub-btn").show();
			BindFormData(allocateData);

			//计算已选货品的总数量
			updateSell.allnumAndAllMoney();
			//删除编辑状态下的订单明细
			updateSell.deleteUpdateGoodsDetail({
				"update": ".update-trash", //删除按钮
				"goodsInList": ".production-edit", //移除页面元素
				"data": allocateData,
				"updateArr": allocateData.whAllocateDetail,
				"sellData": "allotData" //需要存储的数组对象
			}, CheckIfShowPanel);

		}

		var allocateID = sessionStorage.getItem("allocateID");
		if(sessionStorage.goodsInfoList && sessionStorage.goodsInfoList !== undefined) {
			//计算总数量与金额
			updateSell.allnumAndAllMoney();
			//删除订单明细
			var goodsLists = JSON.parse(sessionStorage.goodsInfoList);
			updateSell.deleteGoodsDetail({
				"delete": ".delete-trash", //删除按钮
				"array": goodsLists, //需要删除的数组
				"goodsIn": ".production-add", //移除页面元素
				"goodsInfoList": "goodsInfoList", //需要存储的数组对象
			}, CheckIfShowPanel);
		}

		//调出仓库选择点击事件
		mui('body').on('tap', '#out_whLI', function() {
			sessionStorage.setItem('whLIState', 'state1');
		});

		//调入仓库选择按钮点击事件
		mui('body').on('tap', '#in_whLI', function() {
			sessionStorage.setItem('whLIState', 'state2');
		});

		//货品选择按钮点击事件
		mui('body').on('tap', '#procuctSearch', function(event) {
			var out_whId = $("#out_wh").attr("data-id");
			if(out_whId === "" || typeof(out_whId) == "undefined") {
				muiTips.alertTips(' ', '请先选择调出仓库', 2, 2, 'default');
				return false;
			} else {
				document.location.href = "../chioceProduct/chioceProduct.html";
			}
			sessionStorage.setItem('productSelectSource', 'allot');
			if(actionType == 1) {
				sessionStorage.setItem('whLIState', 'state3');
			}
			sessionStorage.removeItem("localstatusType");
			sessionStorage.removeItem("statusType");
			sessionStorage.removeItem("goodsId");
		});

		//新增数据状态  货品明细列表项点击事件 
		mui("body").on("tap", "#goodsListShow .production-add", function() {
			sessionStorage.setItem('productSelectSource', 'allot');
			sessionStorage.setItem("goodsIndex", $(this).attr("data-id"));
			sessionStorage.setItem("localstatusType", $(this).attr("data-other"));
			sessionStorage.removeItem("statusType");
			sessionStorage.removeItem("goodsId");

		});

		//编辑数据状态 货品明细列表项点击事件
		mui("body").on("tap", "#goodsListShow .production-edit", function() {
			sessionStorage.setItem('productSelectSource', 'allot');
			sessionStorage.setItem("goodsIndex", $(this).attr("data-id"));
			sessionStorage.setItem("statusType", $(this).attr("data-other"));
			sessionStorage.removeItem("localstatusType");
			sessionStorage.removeItem("goodsId");
		});

		//提交审核按钮事件
		mui("body").on("tap", ".mui-btn-sub", function() {
			if(CheckCanSave()) {
				var dataModel = GetFormData(abp.statusId.Finish);
				if(dataModel.outWhId === dataModel.inWhId) {
					muiTips.alertTips(' ', '调出仓库和调入仓库不能相同', 2, 2, 'default');
					return false;
				}
				if(!dataModel.id || dataModel.id == "undefined") {
					globalInit.buttonInit(".mui-btn-sub");
					Create(dataModel);
				} else {
					globalInit.buttonInit(".mui-btn-sub");
					Update(dataModel);
				}
			}

		});

		//保存草稿按钮事件
		mui("body").on("tap", ".keep-draft", function() {
			if(CheckCanSave()) {
				var dataModel = GetFormData(abp.statusId.Draft);
				if(dataModel.outWhId === dataModel.inWhId) {
					muiTips.alertTips(' ', '调出仓库和调入仓库不能相同', 2, 2, 'default');
					return false;
				}
				if(!dataModel.id || dataModel.id == "undefined") {
					globalInit.buttonInit(".mui-btn-sub");
					Create(dataModel);
				} else {
					globalInit.buttonInit(".mui-btn-sub");
					Update(dataModel);
				}
			}
		});

		//点击返回清楚缓存
		mui("body").on("tap", "header>button", function() {
			ClearSession();
		});

		//从缓存取数据填充界面元素   
		RenderingValue();

		//检查是否满足显示操作面板方法
		CheckIfShowPanel();

		//检查是否满足保存提交数据方法
		function CheckCanSave() {
			var out_whId = $("#out_wh").attr("data-id");
			var in_whId = $("#in_wh").attr("data-id");
			var staff_userId = $("#staff-user").attr("data-id");
			//alert(staff_userId);
			if(out_whId === "" || typeof(out_whId) == "undefined") {
				muiTips.alertTips(' ', '调出仓库必须选择', 2, 2, 'default');
				return false;
			} else if(in_whId === "" || typeof(in_whId) == "undefined") {
				muiTips.alertTips(' ', '调入仓库必须选择', 2, 2, 'default');
				return false;
			} else if(staff_userId === "" || typeof(staff_userId) == "undefined") {
				muiTips.alertTips(' ', '调拨人必须选择', 2, 2, 'default');
				return false;
			}

			return true;
		}

		//   //计算已选货品的总数量		
		//	 function CalcTotalNumber()
		{
			var allnumber, totalAmount;
			var arrays = [];
			var lastMoney = [];
			//遍历所有货品的数量
			$.each($("#goodsListShow .goodsNum"), function(i, v) {
				allnumber = Number($(v).text());
				arrays.push(allnumber);
			});
			//统计总数量
			for(var i = 0; i < arrays.length - 1; i++) {
				allnumber += arrays[i];
			}
			$("#allNum").text(allnumber);
			//遍历所有货品的金额
			$.each($("#goodsListShow .production-item"), function(i, v) {
				totalAmount = Number($(v).attr("data-amount"));
				lastMoney.push(totalAmount);
			});
			//console.log(lastMoney);
			//统计总金额
			for(var i = 0; i < lastMoney.length - 1; i++) {
				totalAmount += lastMoney[i];
			}
			$("#allPrice").text(Number(totalAmount).toFixed(2));
		}

		//从缓存取数据填充界面元素     
		function RenderingValue() {

			//根据仓库的选择类型分别存储仓库名称及编号
			if(sessionStorage.libraryName && typeof(sessionStorage.libraryName) != "undefined") {
				if(sessionStorage.getItem('whLIState') == 'state1') {
					sessionStorage.setItem('outLibrary', sessionStorage.libraryName + ',' + sessionStorage.libraryNameId);
					sessionStorage.setItem('outLibraryId', sessionStorage.libraryNameId);
				} else if(sessionStorage.getItem('whLIState') == 'state2') {
					sessionStorage.setItem('inLibrary', sessionStorage.libraryName + ',' + sessionStorage.libraryNameId);
				} else if(sessionStorage.getItem('whLIState') == 'state3') {

				}
			}

			//填充调出仓库
			var outWhName = $("#out_wh").text();
			if(sessionStorage.outLibrary && typeof(sessionStorage.outLibrary) != 'undefined') { //调出仓
				var outWhdata = sessionStorage.outLibrary.split(',');
				$("#out_wh").text(outWhdata[0]);
				$("#out_wh").attr("data-id", outWhdata[1]);
			} else {
				if(!outWhName || outWhName === undefined) {
					$("#out_wh").text("选择仓库");
				} else {
					$("#out_wh").text(outWhName);
				}
			}
			//填充调入仓库
			var inWhName = $("#in_wh").text();
			if(sessionStorage.inLibrary && typeof(sessionStorage.inLibrary) != 'undefined') { //调入仓
				var inWhdata = sessionStorage.inLibrary.split(',');
				$("#in_wh").text(inWhdata[0]);
				$("#in_wh").attr("data-id", inWhdata[1]);
			} else {
				if(!inWhName || inWhName === undefined) {
					$("#in_wh").text("选择仓库");
				} else {
					$("#in_wh").text(inWhName);
				}
			}

			//填充调拨人
			var chioceInfo = require("./chioceInfo.js");
			chioceInfo.chioceMore();
		}

		//生成单号   
		function GenerateCode() {
			if(sessionStorage.serialNo) {
				$("#code").text(sessionStorage.serialNo);
				return false;
			}
			var option = {};
			var dataModel = {
				"sourceType": abp.sourceType.WH_ALLOCATE
			};
			abp.services.app.sysClientSettingNumber.getSerialNo(dataModel, option)
				.done(function(data) {
					//console.log(data);
					$("#code").text(data.serialNo);
					sessionStorage.setItem('serialNo', data.serialNo);
					if(data.success) {
						//console.log(data);
					} else {}
				})
				.fail(function(data) {
					mui.alert('<ul class="mui-row pop-tabmain"><li class="mui-col-xs-6 mui-col-sm-6"style="text-align: right;padding-right: 20px;"><a class="yuanico"><span>×</span></a></li><li class="mui-col-xs-6 mui-col-sm-6" style="text-align: left;line-height: 46px;">' + data.message + '</li></ul>', ' ', function() {}, 'div');
				});

		}

		//检查是否满足显示操作面板方法
		function CheckIfShowPanel() {
			if(($("#goodsListShow .product").length > 0) && $("#out_wh").attr("data-id") && $("#in_wh").attr("data-id") && $("#staff-user").attr("data-id")) {
				$("#sub-btn").show();
			} else {
				$("#sub-btn").hide();
			}
			if($("#goodsListShow .product").length > 0) {
				$("#lastInfo").show();
			} else {
				$("#lastInfo").hide();
			}

		}

		//编辑状态下绑定表单数据
		function BindFormData(allocateData) {

			$("#code").text(allocateData.serialNO);
			$("#serialDate").text(allocateData.serialDate.substring(0, 10));
			$("#serialDate").text(allocateData.serialDate.substring(0, 10));
			$("#out_wh").text(allocateData.outWhName);
			$("#out_wh").attr("data-id", allocateData.outWhID);
			sessionStorage.setItem('outLibraryId', allocateData.outWhID);
			sessionStorage.setItem('outLibrary', allocateData.outWhName + ',' + allocateData.outWhID);
			$("#in_wh").text(allocateData.inWhName);
			$("#in_wh").attr("data-id", allocateData.inWhId);
			$("#staff-user").text(allocateData.busUserName);
			$("#staff-user").attr("data-id", allocateData.busUserId);
			$("#remarks").val(allocateData.notes);

			var data = {};
			data.list = allocateData.whAllocateDetail;
			var html = template('goodsList_update', data);
			$("#goodsListShow").show();
			$("#goodsListShow").prepend(html);

		}

		//获取表单数据方法
		function GetFormData(statusId) {
			var serialNo = $("#code").text().trim(); //调拨单号
			var dataCreated = $(".createDate").text().trim(); //调拨日期		
			var out_wh = $("#out_wh").attr("data-id"); //调出仓
			var in_wh = $("#in_wh").attr("data-id"); //调出仓
			var allocate_user_id = $("#staff-user").attr("data-id"); //调拨人					
			var notes = $(".remarks").val().trim(); //备注                	
			var option = {};
			var dataModel = {
				"serialNo": serialNo, //单号
				"outWhId": out_wh, //调出仓库Id
				"inWhId": in_wh, //调入仓库Id
				"deptId": 0, //部门Id        		
				"statusId": statusId, //单据状态	        		
				"notes": notes, //备注	        		
				"serialDate": dataCreated, //单据日期	        		
				"busUserId": allocate_user_id, //业务员Id	     
				"id": allocateID //单据Id
			};
			dataModel.WhAllocateDetail = [];

			var goodsItmes = $(".product");
			for(var i = 0; i < goodsItmes.length; i++) {
				var goodsId = Number($(".product").eq(i).find(".goodsSerial").attr("data-id"));
				var goodsName = $(".product").eq(i).find(".goodsName").text();
				var goodsNumber = Number($(".product").eq(i).find(".goodsNum").text());
				var goodsUnit = $(".product").eq(i).find(".goodsSerial").attr("data-unit");
				var BatchDetail = [];
				var WhAllocateDetailInput = {
					"outWhId": out_wh, // (int): 出库仓位 ,
					"inWhId": in_wh, // (int): 入库仓位 ,
					"goodsId": goodsId, // (int): 货品id ,
					"unit": goodsUnit, // (string): 单位 ,
					"unitCode": goodsUnit, // (string): 副单位 ,
					"unitCodeNumber": goodsNumber, // (decimal): 副单位数量 ,
					"unitCodeConvertRate": 1, // (decimal): 转换率 ,
					"notes": "", // (string): 备注 ,	
					"outStorageId": 0, //(int)出库储位id
					"inStorageId": 0, //(int)入库储位id
					"batchDetail": BatchDetail,
				};
				dataModel.WhAllocateDetail.push(WhAllocateDetailInput);
			}

			return dataModel;
		}

		var option = {};
		//新增数据方法
		function Create(dataModel) {
			abp.services.app.whAllocateList.create(dataModel, option)
				.done(function(data) {
					if(dataModel.statusId == abp.statusId.Draft) {
						muiTips.alertTips(' ', '保存成功', 1, 3, function() {
							document.location.href = "../allocationStock/index.html";
						});
					} else {
						muiTips.alertTips(' ', '提交成功', 1, 3, function() {
							document.location.href = "../allocationStock/index.html";
						});
					}

					ClearSession();
					//sessionStorage.removeItem("allocateID");
					sessionStorage.removeItem("outLibraryId");
					if(data.success) {
						//console.log(data);
					} else {}
				})
				.fail(function(data) {
					mui.alert('<ul class="mui-row pop-tabmain"><li class="mui-col-xs-6 mui-col-sm-6"style="text-align: right;padding-right: 20px;"><a class="yuanico"><span>×</span></a></li><li class="mui-col-xs-6 mui-col-sm-6" style="text-align: left;line-height: 46px;">' + data.message + '</li></ul>', ' ', function() {}, 'div');
					globalInit.buttonReset(".btnDisabledText");
				});
		}

		//修改数据方法
		function Update(dataModel) {
			abp.services.app.whAllocateList.update(dataModel, option)
				.done(function(data) {
					if(dataModel.statusId == abp.statusId.Draft) {

						muiTips.alertTips(' ', '保存成功', 1, 3, ClearSessionDD);
					} else {
						muiTips.alertTips(' ', '提交成功', 1, 3, ClearSessionDD);
					}
					ClearSession();
					//sessionStorage.removeItem("allocateID");
					sessionStorage.removeItem("outLibraryId");
					//document.location.href='../allocationStock/index.html';
					if(data.success) {
						//console.log(data);
					} else {}
				})
				.fail(function(data) {
					mui.alert('<ul class="mui-row pop-tabmain"><li class="mui-col-xs-6 mui-col-sm-6"style="text-align: right;padding-right: 20px;"><a class="yuanico"><span>×</span></a></li><li class="mui-col-xs-6 mui-col-sm-6" style="text-align: left;line-height: 46px;">' + data.message + '</li></ul>', ' ', function() {}, 'div');
					globalInit.buttonReset(".btnDisabledText");
				});
		}

		//清楚缓存公调方法	
		function ClearSession() {
			sessionStorage.removeItem("serialNo");
			sessionStorage.removeItem("libraryName");
			sessionStorage.removeItem("libraryNameId");
			sessionStorage.removeItem("outLibraryId");
			sessionStorage.removeItem("outLibrary");
			sessionStorage.removeItem("inLibrary");
			sessionStorage.removeItem("chioceStaff");
			sessionStorage.removeItem("allotData");
			sessionStorage.removeItem("clientId");
			sessionStorage.removeItem("goodsInfoList");
			sessionStorage.removeItem("statusType");
			sessionStorage.removeItem("localstatusType");
			sessionStorage.removeItem("whLIState");
			sessionStorage.removeItem("createHome");
			//			document.location.href = "../../src/allocationStock/allocationStockDetail.html";
		}
		//清楚缓存钉钉公调方法	
		function ClearSessionDD() {
			ClearSession();
			document.location.href = "../../src/allocationStock/allocationStockDetail.html?dd_nav_bgcolor=FFFF943E";
		}
		//清楚缓存钉钉公调方法	
		function ClearSessionDDCreate() {
			ClearSession();
			document.location.href = "../../src/allocationStock/index.html?dd_nav_bgcolor=FFFF943E";
		}
		//清楚缓存钉钉公调方法	首页
		function ClearSessionDDCreateHome() {
			ClearSession();
			document.location.href = "../../src/index.html?dd_nav_bgcolor=FFFF943E";
		}
		//钉钉返回清除缓存
		if(sessionStorage.getItem("allotData")) {
			//ios
			dingTalkNav.LeftNavBar(ClearSessionDD);
			//AD
			dingTalkNav.leftAndroid(ClearSessionDD);
			//update
			dingTalkNav.setTitleText("编辑库存调拨");
		} else if(sessionStorage.getItem("createHome")) {
			//ios
			dingTalkNav.LeftNavBar(ClearSessionDDCreateHome);
			//AD
			dingTalkNav.leftAndroid(ClearSessionDDCreateHome);
		} else {
			//ios
			dingTalkNav.LeftNavBar(ClearSessionDDCreate);
			//AD
			dingTalkNav.leftAndroid(ClearSessionDDCreate);
			//create
			dingTalkNav.setTitleText("新增库存调拨");
		}

	});

	//判断是否启用审批
	var eHistory = require("eHistory");
	var isExamina = eHistory.funIsAuditSetting(abp.sourceType.WH_ALLOCATE, examinaSourceId);
	if(isExamina === true) {
		$("#btnSubmitExamina").text("提交审核");
	} else {
		$("#btnSubmitExamina").text("提交");
	}

});